// pages/health/index.js
const app = getApp();
const themeManager = require('../../utils/theme-manager');
const storage = require('../../utils/storage');

Page({
  data: {
    // 主题相关
    currentTheme: 'pink',
    themeColors: {},
    
    // 用户信息
    userInfo: {},
    
    // 生理期数据
    cycleData: {
      lastPeriodDate: null,
      cycleLength: 28,
      periodLength: 5,
      nextPeriodDate: null,
      daysUntilNext: 0,
      currentPhase: 'follicular', // follicular, ovulation, luteal, menstrual
      phaseDay: 1
    },
    
    // 今日状态
    todayStatus: {
      date: '',
      phase: '',
      symptoms: [],
      mood: '',
      energy: 0,
      notes: ''
    },
    
    // 症状追踪
    symptoms: [
      { id: 'cramps', name: '痛经', icon: '🤕', selected: false },
      { id: 'bloating', name: '腹胀', icon: '🎈', selected: false },
      { id: 'headache', name: '头痛', icon: '😵', selected: false },
      { id: 'fatigue', name: '疲劳', icon: '😴', selected: false },
      { id: 'mood_swings', name: '情绪波动', icon: '😢', selected: false },
      { id: 'acne', name: '痘痘', icon: '😰', selected: false },
      { id: 'breast_tenderness', name: '乳房胀痛', icon: '💔', selected: false },
      { id: 'back_pain', name: '腰痛', icon: '🦴', selected: false }
    ],
    
    // 心情选项
    moods: [
      { id: 'happy', name: '开心', emoji: '😊', color: '#FFD700' },
      { id: 'calm', name: '平静', emoji: '😌', color: '#87CEEB' },
      { id: 'anxious', name: '焦虑', emoji: '😰', color: '#FFA500' },
      { id: 'sad', name: '难过', emoji: '😢', color: '#6495ED' },
      { id: 'angry', name: '愤怒', emoji: '😠', color: '#FF6347' },
      { id: 'tired', name: '疲惫', emoji: '😴', color: '#9370DB' }
    ],
    
    // 健康建议
    healthTips: [],
    
    // 统计数据
    statistics: {
      averageCycleLength: 28,
      averagePeriodLength: 5,
      totalCycles: 0,
      lastUpdated: null
    },
    
    // UI状态
    showSymptomModal: false,
    showMoodModal: false,
    showTipsModal: false,
    showStatsModal: false,
    
    // 动画状态
    animationData: {},
    phaseAnimation: {},
    
    // 加载状态
    loading: true
  },

  onLoad(options) {
    this.initTheme();
    this.initAnimations();
    this.loadUserData();
    this.loadHealthData();
    this.calculateCycleInfo();
    this.generateHealthTips();
    this.setData({ loading: false });
  },

  onShow() {
    this.refreshTodayStatus();
    this.updatePhaseAnimation();
  },

  // 初始化主题
  initTheme() {
    const userInfo = app.globalData.userInfo || {};
    const theme = userInfo.role === 'male' ? 'gold' : 'pink';
    const colors = themeManager.getThemeColors(theme);
    
    this.setData({
      currentTheme: theme,
      themeColors: colors,
      userInfo: userInfo
    });
  },

  // 初始化动画
  initAnimations() {
    const animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease-in-out'
    });
    
    const phaseAnimation = wx.createAnimation({
      duration: 2000,
      timingFunction: 'ease-in-out',
      delay: 500
    });
    
    this.setData({
      animationData: animation.export(),
      phaseAnimation: phaseAnimation.export()
    });
  },

  // 加载用户数据
  loadUserData() {
    const userInfo = storage.get('userInfo') || {};
    this.setData({ userInfo });
  },

  // 加载健康数据
  loadHealthData() {
    const cycleData = storage.get('cycleData') || this.data.cycleData;
    const statistics = storage.get('healthStatistics') || this.data.statistics;
    const todayStatus = storage.get(`healthStatus_${this.getTodayString()}`) || this.data.todayStatus;
    
    this.setData({
      cycleData,
      statistics,
      todayStatus
    });
  },

  // 计算周期信息
  calculateCycleInfo() {
    const { cycleData } = this.data;
    
    if (!cycleData.lastPeriodDate) {
      return;
    }
    
    const lastPeriod = new Date(cycleData.lastPeriodDate);
    const today = new Date();
    const daysSinceLastPeriod = Math.floor((today - lastPeriod) / (1000 * 60 * 60 * 24));
    
    // 计算下次月经日期
    const nextPeriodDate = new Date(lastPeriod);
    nextPeriodDate.setDate(nextPeriodDate.getDate() + cycleData.cycleLength);
    
    const daysUntilNext = Math.floor((nextPeriodDate - today) / (1000 * 60 * 60 * 24));
    
    // 确定当前阶段
    let currentPhase = 'follicular';
    let phaseDay = daysSinceLastPeriod + 1;
    
    if (daysSinceLastPeriod < cycleData.periodLength) {
      currentPhase = 'menstrual';
    } else if (daysSinceLastPeriod >= 12 && daysSinceLastPeriod <= 16) {
      currentPhase = 'ovulation';
    } else if (daysSinceLastPeriod > 16) {
      currentPhase = 'luteal';
    }
    
    this.setData({
      'cycleData.nextPeriodDate': nextPeriodDate.toISOString().split('T')[0],
      'cycleData.daysUntilNext': daysUntilNext,
      'cycleData.currentPhase': currentPhase,
      'cycleData.phaseDay': phaseDay
    });
    
    // 保存数据
    storage.set('cycleData', this.data.cycleData);
  },

  // 生成健康建议
  generateHealthTips() {
    const { currentPhase } = this.data.cycleData;
    let tips = [];
    
    switch (currentPhase) {
      case 'menstrual':
        tips = [
          { icon: '🌡️', title: '保暖', content: '注意腹部和腰部保暖，可以用热水袋缓解疼痛' },
          { icon: '🥛', title: '补铁', content: '多吃富含铁质的食物，如红肉、菠菜、豆类' },
          { icon: '😴', title: '休息', content: '保证充足睡眠，避免剧烈运动' },
          { icon: '🧘‍♀️', title: '放松', content: '可以做轻柔的瑜伽或冥想来缓解不适' }
        ];
        break;
      case 'follicular':
        tips = [
          { icon: '💪', title: '运动', content: '这是运动的好时机，可以进行力量训练' },
          { icon: '🥗', title: '营养', content: '多吃新鲜蔬果，补充维生素和矿物质' },
          { icon: '📚', title: '学习', content: '精力充沛，适合学习新技能或制定计划' },
          { icon: '💡', title: '创意', content: '思维活跃，是发挥创造力的好时期' }
        ];
        break;
      case 'ovulation':
        tips = [
          { icon: '💃', title: '社交', content: '魅力值最高的时期，适合社交活动' },
          { icon: '🏃‍♀️', title: '有氧运动', content: '可以进行有氧运动，如跑步、游泳' },
          { icon: '💧', title: '补水', content: '多喝水，保持身体水分充足' },
          { icon: '🌟', title: '自信', content: '感受自己的美丽，展现自信的一面' }
        ];
        break;
      case 'luteal':
        tips = [
          { icon: '🍫', title: '控制食欲', content: '可能会有食欲增加，注意控制糖分摄入' },
          { icon: '😌', title: '情绪管理', content: '可能情绪波动较大，多做放松活动' },
          { icon: '🛁', title: '护肤', content: '皮肤可能较敏感，选择温和的护肤品' },
          { icon: '📝', title: '记录', content: '记录身体变化，为下个周期做准备' }
        ];
        break;
    }
    
    this.setData({ healthTips: tips });
  },

  // 刷新今日状态
  refreshTodayStatus() {
    const today = this.getTodayString();
    const todayStatus = storage.get(`healthStatus_${today}`) || {
      date: today,
      phase: this.data.cycleData.currentPhase,
      symptoms: [],
      mood: '',
      energy: 0,
      notes: ''
    };
    
    this.setData({ todayStatus });
  },

  // 更新阶段动画
  updatePhaseAnimation() {
    const animation = wx.createAnimation({
      duration: 2000,
      timingFunction: 'ease-in-out'
    });
    
    animation.scale(1.1).step().scale(1).step();
    
    this.setData({
      phaseAnimation: animation.export()
    });
  },

  // 获取今日日期字符串
  getTodayString() {
    return new Date().toISOString().split('T')[0];
  },

  // 记录月经开始
  onRecordPeriod() {
    const today = new Date().toISOString().split('T')[0];
    
    wx.showModal({
      title: '记录月经',
      content: '确认今天是月经第一天吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            'cycleData.lastPeriodDate': today
          });
          
          this.calculateCycleInfo();
          this.generateHealthTips();
          
          wx.showToast({
            title: '记录成功',
            icon: 'success'
          });
        }
      }
    });
  },

  // 打开症状记录
  onOpenSymptomModal() {
    // 加载今日已选择的症状
    const selectedSymptoms = this.data.todayStatus.symptoms || [];
    const symptoms = this.data.symptoms.map(symptom => ({
      ...symptom,
      selected: selectedSymptoms.includes(symptom.id)
    }));
    
    this.setData({
      symptoms,
      showSymptomModal: true
    });
  },

  // 选择症状
  onSelectSymptom(e) {
    const { index } = e.currentTarget.dataset;
    const symptoms = [...this.data.symptoms];
    symptoms[index].selected = !symptoms[index].selected;
    
    this.setData({ symptoms });
  },

  // 保存症状
  onSaveSymptoms() {
    const selectedSymptoms = this.data.symptoms
      .filter(symptom => symptom.selected)
      .map(symptom => symptom.id);
    
    const todayStatus = {
      ...this.data.todayStatus,
      symptoms: selectedSymptoms
    };
    
    this.setData({
      todayStatus,
      showSymptomModal: false
    });
    
    // 保存到本地存储
    storage.set(`healthStatus_${this.getTodayString()}`, todayStatus);
    
    wx.showToast({
      title: '保存成功',
      icon: 'success'
    });
  },

  // 打开心情记录
  onOpenMoodModal() {
    this.setData({ showMoodModal: true });
  },

  // 选择心情
  onSelectMood(e) {
    const { mood } = e.currentTarget.dataset;
    
    const todayStatus = {
      ...this.data.todayStatus,
      mood: mood
    };
    
    this.setData({
      todayStatus,
      showMoodModal: false
    });
    
    // 保存到本地存储
    storage.set(`healthStatus_${this.getTodayString()}`, todayStatus);
    
    wx.showToast({
      title: '记录成功',
      icon: 'success'
    });
  },

  // 更新能量值
  onEnergyChange(e) {
    const energy = e.detail.value;
    
    const todayStatus = {
      ...this.data.todayStatus,
      energy: energy
    };
    
    this.setData({ todayStatus });
    
    // 保存到本地存储
    storage.set(`healthStatus_${this.getTodayString()}`, todayStatus);
  },

  // 更新备注
  onNotesInput(e) {
    const notes = e.detail.value;
    
    const todayStatus = {
      ...this.data.todayStatus,
      notes: notes
    };
    
    this.setData({ todayStatus });
    
    // 保存到本地存储
    storage.set(`healthStatus_${this.getTodayString()}`, todayStatus);
  },

  // 查看健康建议
  onShowTips() {
    this.setData({ showTipsModal: true });
  },

  // 查看统计数据
  onShowStats() {
    this.calculateStatistics();
    this.setData({ showStatsModal: true });
  },

  // 计算统计数据
  calculateStatistics() {
    // 这里可以添加更复杂的统计计算逻辑
    const statistics = {
      ...this.data.statistics,
      lastUpdated: new Date().toISOString()
    };
    
    this.setData({ statistics });
    storage.set('healthStatistics', statistics);
  },

  // 跳转到日历页面
  onGoToCalendar() {
    wx.navigateTo({
      url: '/pages/health/calendar'
    });
  },

  // 关闭弹窗
  onCloseModal() {
    this.setData({
      showSymptomModal: false,
      showMoodModal: false,
      showTipsModal: false,
      showStatsModal: false
    });
  },

  // 分享健康数据
  onShareHealth() {
    const { currentPhase, daysUntilNext } = this.data.cycleData;
    
    return {
      title: `我的生理期健康管理 - 当前${this.getPhaseText(currentPhase)}期`,
      path: '/pages/health/index',
      imageUrl: '/images/health-share.png'
    };
  },

  // 获取阶段文本
  getPhaseText(phase) {
    const phaseMap = {
      'menstrual': '月经',
      'follicular': '卵泡',
      'ovulation': '排卵',
      'luteal': '黄体'
    };
    return phaseMap[phase] || '未知';
  },

  // 获取阶段颜色
  getPhaseColor(phase) {
    const colors = {
      'menstrual': '#FF6B6B',
      'follicular': '#4ECDC4', 
      'ovulation': '#45B7D1',
      'luteal': '#96CEB4'
    };
    return colors[phase] || '#999999';
  },

  // 获取当前心情信息的辅助方法
  getCurrentMoodEmoji() {
    if (!this.data.todayStatus.mood) return '😊';
    const mood = this.data.moods.find(m => m.id === this.data.todayStatus.mood);
    return mood ? mood.emoji : '😊';
  },

  getCurrentMoodName() {
    if (!this.data.todayStatus.mood) return '点击记录';
    const mood = this.data.moods.find(m => m.id === this.data.todayStatus.mood);
    return mood ? mood.name : '点击记录';
  },

  onShareAppMessage() {
    return this.onShareHealth();
  }
});